package com.niit.order.web;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheKey;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
import com.niit.order.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;



/**
 * 开启请求缓存
 * 清除缓存案例
 * @author yaojianfeng
 */
@RestController
@RequestMapping("/consumer")
public class HystrixConsumerController03 {
    @Autowired
    private RestTemplate restTemplate;


    /**
     * 获取用户信息 开启缓存
     * @param id
     * @return
     */
    @GetMapping("/user/{id}")
    @HystrixCommand(fallbackMethod = "getUserInfoFallback")
    @CacheResult(cacheKeyMethod = "cacheKey")
    public User getUserInfo(@PathVariable("id")@CacheKey String id) {
        String url = "http://userservice/user/" + id;
        return restTemplate.getForObject(url, User.class);
    }

    public User getUserInfoFallback(String id) {
        User user = new User();
        user.setUsername("服务器故障");
        user.setAddress("郑州");
        Long userId = Long.parseLong(id);
        user.setId(userId);
        return user;
    }

    public String cacheKey(String id){
        return id;
    }

//*============================下面是缓存清除案例==========================================
//*==================================案例================================================


    @GetMapping("/getUserById/{id}")
    @HystrixCommand(fallbackMethod = "getUserInfoFallback")
    @CacheResult(cacheKeyMethod = "cacheKey")
    public User getUserById(@PathVariable("id") @CacheKey String id) {
        String url = "http://userservice/user/" + id;
        return restTemplate.getForObject(url, User.class);
    }

    /**
     * 更新操作需要清除缓存
     * @param user
     * @return
     */
    @CacheRemove(commandKey = "getUserById")
    @HystrixCommand(fallbackMethod = "updateFallback")
    @PostMapping("/update")
    public User update(@CacheKey("id") @RequestBody User user) {
        return restTemplate.postForObject("http://userservice/user/update", user, User.class);
    }
    public User updateFallback(User user) {
        user.setUsername("更新失败!");
        return user;
    }

}
